<template>
  <div class="login-container">
    <div class="login-left">
      <img :src="loginBg" alt="Login background" class="login-bg" />
    </div>
    <div class="login-right">
      <div class="login-form">
        <h1>管理员登录</h1>
        <p class="subtitle">欢迎使用证书管理系统</p>

        <div class="form-container">
          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="rules"
            label-width="0"
            @keyup.enter="handleLogin"
          >
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" placeholder="用户名" :prefix-icon="User" />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="密码"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                class="login-button"
                :loading="loading"
                @click="handleLogin"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 错误提示区域 -->
          <div v-if="loginError" class="login-error">
            {{ loginError }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
import { adminApi } from '@/api/adminApi'
import { useUserStore } from '@/stores/user'
import loginBg from '@/assets/images/login-bg.jpg'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const loginFormRef = ref(null)
const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: ''
})

const validateUsername = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入用户名'))
  } else {
    callback()
  }
}

const validatePassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入密码'))
  } else {
    callback()
  }
}

const rules = {
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }]
}

// 添加错误信息的响应式变量
const loginError = ref('')

const handleLogin = async () => {
  if (!loginFormRef.value) return
  loginError.value = '' // 清空之前的错误信息

  try {
    await loginFormRef.value.validate()
    loading.value = true
    const res = await adminApi.login(loginForm.username, loginForm.password)

    // 只在成功响应时才进行后续操作
    if (res.code === 200 && res.data && res.data.token) {
      userStore.login(res.data)
      const redirect = route.query.redirect?.toString()
      router.push(redirect || '/admin/certificates')
    } else {
      loginError.value = res.message || '登录失败'
      loginForm.password = ''
    }
  } catch (error) {
    console.error('Login error:', error)
    // 根据错误类型显示不同的提示信息
    if (error.response) {
      switch (error.response.status) {
        case 401:
          loginError.value = '用户名或密码错误'
          break
        case 429:
          loginError.value = '登录尝试次数过多，请稍后再试'
          break
        case 500:
          loginError.value = '服务器错误，请稍后再试'
          break
        default:
          loginError.value = error.response.data?.message || '登录失败'
      }
    } else if (error.request) {
      loginError.value = '网络连接失败，请检查网络'
    } else {
      loginError.value = error.message || '登录失败'
    }
    // 登录失败时清空密码
    loginForm.password = ''
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  width: 100vw;
  display: flex;
  background-color: #000;
}

.login-left {
  flex: 1.2;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #000;
}

.login-bg {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: center;
}

.login-right {
  position: relative;
  width: 500px;
  padding: 0 60px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  box-shadow: -10px 0 30px rgba(0, 0, 0, 0.15);
  z-index: 1;
}

.login-form {
  width: 100%;
  position: relative;
}

h1 {
  font-size: 32px;
  font-weight: 500;
  color: #1e293b;
  margin-bottom: 12px;
}

.subtitle {
  color: #64748b;
  font-size: 16px;
  margin-bottom: 48px;
}

/* 添加表单容器样式 */
.form-container {
  min-height: 280px; /* 设置一个固定的最小高度，确保有足够空间容纳错误提示 */
  position: relative;
}

:deep(.el-input__wrapper) {
  background-color: #f8fafc;
  box-shadow: 0 0 0 1px rgba(229, 231, 235, 0.6);
  height: 48px;
  padding: 0 16px;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #3b82f6;
}

:deep(.el-input__inner) {
  height: 48px;
  font-size: 15px;
}

:deep(.el-input__prefix-inner) {
  color: #94a3b8;
  font-size: 18px;
}

.login-button {
  width: 100%;
  height: 48px;
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  border: none;
  font-size: 16px;
  font-weight: 500;
  margin-top: 24px;
  transition: all 0.3s ease;
}

.login-button:hover {
  background: linear-gradient(135deg, #2563eb, #1d4ed8);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(37, 99, 235, 0.2);
}

/* 自适应设计 */
@media screen and (max-width: 1280px) {
  .login-right {
    width: 450px;
    padding: 0 40px;
  }

  .login-left {
    flex: 1;
  }

  .login-bg {
    transform: scale(1.05);
  }
}

/* 全局样式，确保在最外层 */
:global(.login-error-message) {
  min-width: 380px !important;
  padding: 15px 20px !important;
  background: rgba(255, 59, 48, 0.9) !important;
  backdrop-filter: blur(10px) !important;
  border: none !important;
  border-radius: 8px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
}

:global(.login-error-message .el-message__content) {
  color: white !important;
  font-size: 15px !important;
  line-height: 1.4 !important;
}

:global(.login-error-message .el-message__closeBtn) {
  color: white !important;
  font-size: 18px !important;
  top: 50% !important;
  transform: translateY(-50%) !important;
}

:global(.login-error-message .el-message__closeBtn:hover) {
  color: rgba(255, 255, 255, 0.8) !important;
}

@media screen and (max-width: 1024px) {
  .login-right {
    width: 400px;
    padding: 0 32px;
  }

  .login-bg {
    transform: scale(1.1);
  }
}

@media screen and (max-width: 768px) {
  .login-container {
    flex-direction: column;
  }

  .login-left {
    display: none;
  }

  .login-right {
    width: 100%;
    min-height: 100vh;
    padding: 40px 24px;
  }

  .login-form {
    max-width: 400px;
    margin: 0 auto;
  }

  h1 {
    font-size: 28px;
    margin-bottom: 8px;
  }

  .subtitle {
    font-size: 15px;
    margin-bottom: 36px;
  }
}

@media screen and (max-width: 480px) {
  .login-right {
    padding: 32px 20px;
  }

  :deep(.el-input__wrapper) {
    height: 44px;
  }

  :deep(.el-input__inner) {
    height: 44px;
    font-size: 14px;
  }

  .login-button {
    height: 44px;
    font-size: 15px;
  }
}

.login-error {
  width: 100%;
  padding: 12px 16px;
  margin-top: 16px;
  background: rgba(255, 59, 48, 0.1);
  border-left: 4px solid #ff3b30;
  border-radius: 4px;
  color: #ff3b30;
  font-size: 14px;
  line-height: 1.4;
  text-align: left;
  transition: all 0.3s ease;
  animation: fadeIn 0.3s ease;
  position: absolute; /* 使用绝对定位 */
  bottom: 0; /* 固定在底部 */
  left: 0; /* 左对齐 */
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
